#!/bin/bash

pluginDir=$1
mirrorDir=$2
# pluginDir="plugins"
# mirrorDir="mirrorPlugins"
# The mirror url for accelerating, ends with '/'
mirrorUrl="https://mirror.ghproxy.com/"

if [ ! -d "$pluginDir" ]; then
    echo "Path $pluginDir does not exists"
    exit
fi

if [ ! -d "$mirrorDir" ]; then
    mkdir -p $mirrorDir
fi

indexJsonFile="$mirrorDir/index.json"

echo "Replace the plugin download url, pluginDir: $pluginDir, mirrorDir: $mirrorDir"

for file in $pluginDir/*.json; do
    echo "::::Processing [$file]"

    if [ $file = "$pluginDir/index.json" ]; then
        echo -e "Copy $file to $indexJsonFile\n"
        jq . $file > $indexJsonFile
        continue
    fi

    pluginName=$(jq -r '.name' $file)
    pluginJsonFile="$mirrorDir/$pluginName.json"

    newDownloadUrl="$mirrorUrl$(jq -r '.downloadUrl' $file)"
    echo "The new downloadUrl is: $newDownloadUrl"
    jq --arg NDL $newDownloadUrl '.downloadUrl = "\($NDL)"' $file > $pluginJsonFile

    echo -e "::::End processing [$pluginJsonFile]\n"
done
